package com.jiuyue.movehouse.common.resolver;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiuyue.movehouse.annotion.PageInfo;
import com.jiuyue.movehouse.common.exception.BadRequestException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author min
 * @description
 * @date 2020/9/12
 */
@Component
public class PageInfoArgResolver implements HandlerMethodArgumentResolver {


    /**
     * 判断是否支持使用@PageInfo注解的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //如果该参数注解有@PageInfo且参数类型是Page
        return methodParameter.getParameterAnnotation(PageInfo.class) != null &&methodParameter.getParameterType() == Page.class;
    }

    /**
     * 注入参数值
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {

        //取得HttpServletRequest
        HttpServletRequest request= (HttpServletRequest) nativeWebRequest.getNativeRequest();
        String pageNum = request.getParameter("current");
        if (StringUtils.isEmpty(pageNum)) {
            throw new BadRequestException("current页码不能为空");
        }
        String pageSize = request.getParameter("size");if (StringUtils.isEmpty(pageSize)) {
            throw new BadRequestException("size每页长度不能为空");
        }
        Page page = new Page( Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        page.setMaxLimit(500L);

        return page;

    }

    public static String filter(String param) {
        return param == null ? null : param.replaceAll("(?i)'|%|--|insert|delete|select|count|group|union|drop|truncate|alter|grant|execute|exec|xp_cmdshell|call|declare|sql", "");
    }
}
